package com.oauth.config;

import com.oauth.filter.LoginFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author liwenjian
 * @date 2021/7/12 17:00
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * HttpSecurity 有三个常用方法来配置：
     * addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter)
     * 在 beforeFilter 之前添加 filter
     * addFilterAfter(Filter filter, Class<? extends Filter> afterFilter)
     * 在 afterFilter 之后添加 filter
     * addFilterAt(Filter filter, Class<? extends Filter> atFilter)
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth/**","/login/**","/logout/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf().disable();
    }

    @Bean
    public AuthenticationManager getAuthenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public FilterRegistrationBean sessionFilter(){
        FilterRegistrationBean registration = new FilterRegistrationBean(new LoginFilter());
        registration.addInitParameter("excludedPath","/api/user/login,/swagger-ui.html,/api/hello/*,/api/mysql/*");
        registration.addUrlPatterns("/*");
        return registration;
    }
}
